import React, { useState, useEffect, useRef } from 'react';
import video_1 from '../../../public/video/1.mp4';
import video_2 from '../../../public/video/2.mp4';
import video_3 from '../../../public/video/3.mp4';
import video_4 from '../../../public/video/4.mp4';
import './videos.css';
// 定义一个 Videos 组件
function Videos(): JSX.Element {
    // 定义一个 videoSources 数组，包含四个视频源
    const videoFiles: string[] = [video_1, video_2, video_3, video_4];
    const [currentVideoIndex, setCurrentVideoIndex] = useState(0); 
    const [progress, setProgress] = useState<number>(0);  // 视频播放进度
    const [danmus, setDanmus] = useState<Array<{
        text: string;
        id: number;
        top: string;
        show: boolean;
        left: string;
        animationDuration: string;
    }>>([]); // 存储弹幕信息
    const [inputText, setInputText] = useState(''); // 弹幕输入框的内容
    const videoRef = useRef<HTMLVideoElement | null>(null);

    // 从本地存储中读取弹幕数据
    useEffect(() => {
        const storedDanmus = localStorage.getItem('danmus');
        if (storedDanmus) {
            setDanmus(JSON.parse(storedDanmus));
        }
    }, []);

    // 更新进度条
    const handleTimeUpdate = () => {
        if (videoRef.current) {
            setProgress((videoRef.current.currentTime / videoRef.current.duration) * 100);
        }
    };

    // 视频播放完后自动播放下一个视频
    const handleVideoEnd = () => {
        const nextIndex = (currentVideoIndex + 1) % videoFiles.length; // 循环播放视频
        setCurrentVideoIndex(nextIndex); // 更新视频索引
    };

    // 添加弹幕的函数
    const addDanmu = (text: string) => {
        const newDanmu = {
            text,  // 弹幕内容
            id: Date.now(),
            top: Math.random() * 100 + '%',  // 随机弹幕位置
            show: true, // 新增 show 状态，初始为 true，表示显示
            left: '100%', // 初始位置在右侧
            animationDuration: Math.random() * 5 + 5 + 's' // 设置弹幕滚动速度
        };
        setDanmus(prevDanmus => [...prevDanmus, newDanmu]);
        // 存储弹幕到本地存储
        localStorage.setItem('danmus', JSON.stringify([...danmus, newDanmu]));
    };

    // 提交弹幕的处理函数
    const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        if (inputText.trim()) {
            addDanmu(inputText); // 添加弹幕
            setInputText(''); // 清空输入框
        }
    };

    // 组件加载后播放视频
    useEffect(() => {
        if (videoRef.current) {
            videoRef.current.play();
        }
    }, [currentVideoIndex]); // 每次切换视频索引时，自动播放新视频

    useEffect(() => {
        const danmuIntervals: NodeJS.Timeout[] = [];
        danmus.forEach((danmu, index) => {
            if (danmu.show) {
                const duration = parseFloat(danmu.animationDuration);
                const interval = setInterval(() => {
                    setDanmus(prevDanmus => prevDanmus.map((prevDanmu, i) => 
                        i === index? {...prevDanmu, left: '-100%', show: false } : prevDanmu
                    ));
                }, duration * 1000);
                danmuIntervals.push(interval);
            }
        });
        return () => {
            danmuIntervals.forEach(interval => clearInterval(interval));
        };
    }, [danmus]);

    return (
        <div style={{ position: 'relative' }}>
            <video
                ref={videoRef}
                className="vidro_sx"
                src={videoFiles[currentVideoIndex]} // 根据当前索引播放视频
                onEnded={handleVideoEnd} // 视频播放完后调用该方法
                autoPlay muted controls
                onTimeUpdate={handleTimeUpdate}
            ></video>
            
            {/* 弹幕容器 */}
            <div style={{ position: 'absolute', top: '26px', right: '25px',overflow: 'hidden', width: '90%', height: '75%', pointerEvents: 'none', zIndex: 999, }}>
                {danmus.map((danmu) => (
                    danmu.show && (
                        <div
                            key={danmu.id}
                            style={{
                                position: 'absolute',
                                top: danmu.top,
                                left: danmu.left,
                                whiteSpace: 'nowrap',
                                color: 'white',
                                fontSize: '24px',
                                animation: `move ${danmu.animationDuration} linear`,
                                animationName: 'move'
                            }}
                        >
                            {danmu.text}
                        </div>
                    )
                ))}
            </div>

            {/* 弹幕输入框 */}
            {/* tyle={{ position: 'absolute', bottom: '20px', width: '100%' }} */}
            <form onSubmit={handleSubmit} className='danmu_form' >
                <input
                    type="text"
                    value={inputText}
                    onChange={(e) => setInputText(e.target.value)}
                    placeholder="输入弹幕内容"
                    // style={{ width: '80%', padding: '10px', fontSize: '16px' }}
                    className='danmu_input'
                />
                <button type="submit" style={{ padding: '10px', fontSize: '16px' }}>↲ </button>
            </form>

            {/* 弹幕样式定义 */}
            <style>
                {`
                    @keyframes move {
                        0% {
                            left: 100%;
                        }
                        100% {
                            left: -100%;
                        }
                    }
                `}
            </style>
        </div>
    );
}

// 导出 Videos 组件
export default Videos;